/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cbs.android.function.qrcodescan;

import android.content.Intent;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.handler.CBSActivityResultHandler;

import java.lang.ref.WeakReference;


public class QRCodeScanFunction {
    private static final int REQUEST_QRCODESCAN = 0xFFBA;

    public interface Extras {
        String Result = "result";
    }

    public static void scan(CBSActivity activity, QRCodeScanHandler handler) {
        activity.addActivityResultHandler(new MyActivityResultHandler(activity, handler));
        Intent intent = new Intent(activity, ScanActivity.class);
        activity.startActivityForResult(intent, REQUEST_QRCODESCAN);
    }

    private static class MyActivityResultHandler implements CBSActivityResultHandler {
        private final WeakReference<CBSActivity> activity;
        private final CBSActivityResultHandler handler;

        public MyActivityResultHandler(CBSActivity activity, CBSActivityResultHandler handler) {
            this.activity = new WeakReference<>(activity);
            this.handler = handler;
        }

        @Override
        public void onActivityResult(int requestCode, int responseCode, Intent intent) {
            if (requestCode == REQUEST_QRCODESCAN) {
                if (handler != null) {
                    handler.onActivityResult(requestCode, responseCode, intent);
                }
                if (activity != null && activity.get() != null) {
                    activity.get().removeActivityResultHandler(this);
                }
            }
        }
    }
}